<?php

namespace app\controllers;

use app\components\BaseController;
use app\models\ContestProblem;
use app\models\ContestUser;
use app\models\Problem;
use app\models\Solution;
use app\models\User;
use Yii;
use app\models\Group;
use yii\data\ActiveDataProvider;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\db\Query;
use yii\filters\AccessControl;
use app\models\Contest;
use app\models\Homework;
use app\models\ContestAnnouncement;
use yii\web\NotFoundHttpException;

/**
 * HomeworkController implements the CRUD actions for Homework model.
 */
class HomeworkController extends BaseController
{
    public function init()
    {
        Yii::$app->language = 'zh-CN';
        parent::init(); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'lastActivity' => [
                'class' => \app\behaviors\LastActivityBehavior::className(),
            ],                
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create'],
                'rules' => [
                    [
                        'actions' => ['create'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * 删除一个问题
     * @param $id
     * @param $pid
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \yii\db\Exception
     */
    public function actionDeleteproblem($id, $pid)
    {
        $model = $this->findModel($id);
        $model->deleteProblem($pid);
        Yii::$app->session->setFlash('success', Yii::t('app', 'Deleted successfully'));
        return $this->redirect(['/homework/update', 'id' => $id]);
    }

    /**
     * 增加一个问题
     * @param $id
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \yii\db\Exception
     */
    public function actionAddproblem($id)
    {
        $model = $this->findModel($id);

        if (($post = Yii::$app->request->post())) {

            $problem_ids  = $post['problem_ids'];
            $cnt = count($problem_ids);
            $info_msg = "";
            for ($i = 0; $i < $cnt; ++$i) {
                if (empty($problem_ids[$i]) || $problem_ids[$i]=='1')
                continue;
                $pid = $problem_ids[$i];

                $problemStatus = (new Query())->select('status')
                    ->from('{{%problem}}')
                    ->where('id=:id', [':id' => $pid])
                    ->scalar();
                if ($problemStatus == null || ($problemStatus == Problem::STATUS_HIDDEN && Yii::$app->user->identity->role != User::ROLE_ADMIN)) {
                    Yii::$app->session->setFlash('error', Yii::t('app', 'No such problem.'));
                } else if ($problemStatus == Problem::STATUS_PRIVATE && (Yii::$app->user->identity->role < User::ROLE_VIP)) {
                        $info_msg = $info_msg.$pid.":".Yii::t('app', '私有题目，普通用户不能选用。')."<br>";
                } else if ($problemStatus >= Problem::STATUS_TEACHER && (Yii::$app->user->identity->role < User::ROLE_TEACHER)) {
                    $info_msg = $info_msg.$pid.":".Yii::t('app', '私有题目，普通用户不能选用。')."<br>";
            } else {
                    $problemInContest = (new Query())->select('problem_id')
                        ->from('{{%contest_problem}}')
                        ->where(['problem_id' => $pid, 'contest_id' => $model->id])
                        ->exists();
                    if ($problemInContest) {
                        $info_msg = $info_msg.$pid.":".Yii::t('app', 'This problem has in the contest.')."<br>";
                        continue;
                    }
                    $count = (new Query())->select('contest_id')
                        ->from('{{%contest_problem}}')
                        ->where(['contest_id' => $model->id])
                        ->count();
    
                    Yii::$app->db->createCommand()->insert('{{%contest_problem}}', [
                        'problem_id' => $pid,
                        'contest_id' => $model->id,
                        'num' => $count
                    ])->execute();
                }
            }
            if($info_msg==""){
                Yii::$app->session->setFlash('success', Yii::t('app', 'Submitted successfully')); 
            }else{
                 Yii::$app->session->setFlash('info', $info_msg);
            } 
        } 
        return $this->redirect(['/homework/update', 'id' => $id]);
    }


    /**
     * 移动一个问题
     * @param $id
     * @param $pid
     * @param $mv
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \yii\db\Exception
     */
    public function actionMoveproblem($id, $pid,$mv)
    {
        $model = $this->findModel($id);
        $new_pid = intval($pid) + intval($mv);
        if($new_pid>=0){
            $problem = $model->getProblemById(intval($pid));
            $new_problem = $model->getProblemById(intval($new_pid));
            if($problem && $new_problem){
                $num = intval($problem['num']);
                $new_num = intval($new_problem['num']);
    
                Yii::$app->db->createCommand()->update('{{%contest_problem}}', [
                    'problem_id' => $new_problem['id'],
                ], ['num' => $num, 'contest_id' => $model->id])->execute();
    
                Yii::$app->db->createCommand()->update('{{%contest_problem}}', [
                    'problem_id' => $problem['id'],
                ], ['num' => $new_num, 'contest_id' => $model->id])->execute();
                Yii::$app->cache->flush();
            }
        }
        return $this->redirect(['/homework/update', 'id' => $id]);
    }



    /**
     * 修改一个问题
     * @param $id
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \yii\db\Exception
     */
    public function actionUpdateproblem($id)
    {
        $model = $this->findModel($id);

        if (($post = Yii::$app->request->post())) {
            $pid = intval($post['problem_id']);
            $new_pid = intval($post['new_problem_id']);

            $oldProblemStatus = (new Query())->select('status')
                ->from('{{%problem}}')
                ->where('id=:id', [':id' => $pid])
                ->scalar();
            $newProblemStatus = (new Query())->select('status')
                ->from('{{%problem}}')
                ->where('id=:id', [':id' => $new_pid])
                ->scalar();

            if (!empty($oldProblemStatus) && !empty($newProblemStatus)) {
                $problemInContest = (new Query())->select('problem_id')
                    ->from('{{%contest_problem}}')
                    ->where(['problem_id' => $new_pid, 'contest_id' => $model->id])
                    ->exists();
                if ($problemInContest) {
                    Yii::$app->session->setFlash('info', Yii::t('app', 'This problem has in the contest.'));
                    return $this->redirect(['/homework/update', 'id' => $id]);
                }
                if ($newProblemStatus == Problem::STATUS_VISIBLE || Yii::$app->user->identity->role == User::ROLE_ADMIN
                    || ($newProblemStatus == Problem::STATUS_PRIVATE && Yii::$app->user->identity->role >= User::ROLE_VIP)
                    || ($newProblemStatus >= Problem::STATUS_TEACHER && Yii::$app->user->identity->role >= User::ROLE_TEACHER)) {
                    Yii::$app->db->createCommand()->update('{{%contest_problem}}', [
                        'problem_id' => $new_pid,
                    ], ['problem_id' => $pid, 'contest_id' => $model->id])->execute();
                    Yii::$app->cache->flush();
                    Yii::$app->session->setFlash('success', Yii::t('app', 'Submitted successfully'));
                }
            } else {
                Yii::$app->session->setFlash('error', Yii::t('app', 'No such problem.'));
            }
            return $this->redirect(['/homework/update', 'id' => $id]);
        }
    }

    /**
     * 从题目中导入解题
     * @param $id
     * @return \yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \yii\db\Exception
     */
    public function actionImport_solution($id)
    {
        $model = $this->findModel($id);
        $solutions = $model->problems_solution;
        $html = "";
        if(Yii::$app->setting->get('ojEditor')=='app\widgets\editormd\Editormd'){
            foreach ($solutions as $key => $p){
                if(!empty($p['solution'])){
                    $html = $html . 'P' . ($key + 1).':'.PHP_EOL.PHP_EOL.$p['solution'].PHP_EOL.PHP_EOL;
                }
            }
        }else{
            foreach ($solutions as $key => $p){
                if(!empty($p['solution'])){
                    $html = $html . '<p>P' . ($key + 1).':</p>'.$p['solution'].'<p>&nbsp;</p>';
                }
            }  
        }

        return $html;
    }

    /**
     * 删除指定的公告。
     * @param integer $contest_id; 比赛id
     * @param integer $id 删除的公告id
     * @return mixed
     */
    public function actionDelete_announcement($contest_id,$id)
    {
        Yii::$app->db->createCommand()->delete('{{%contest_announcement}}',['id' => $id])->execute();
        Yii::$app->session->setFlash('success', Yii::t('app', 'Delete successfully'));
        return $this->redirect(['/homework/update', 'id' => $contest_id]);
    }

    /**
     * @param $id
     * @return string|\yii\web\Response
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionUpdate($id)
    {
        $this->layout = 'main';
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->refresh();
        }

        $announcements = new ActiveDataProvider([
            'query' => ContestAnnouncement::find()->where(['contest_id' => $model->id])
        ]);

        $newAnnouncement = new ContestAnnouncement();
        if ($newAnnouncement->load(Yii::$app->request->post())) {
            $newAnnouncement->contest_id = $model->id;
            $newAnnouncement->save();
            Yii::$app->session->setFlash('success', Yii::t('app', 'Saved successfully'));
            return $this->refresh();
        }

        if (!Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin()) {
            $group_datas = Yii::$app->db->createCommand('SELECT g.id,g.name FROM {{%group}}  AS g LEFT JOIN {{%group_user}} AS u ON u.group_id=g.id WHERE g.id<>:gid AND u.user_id=:id AND is_train=:is_train AND g.status<>:status',
            [':gid' => $model->group->id,':id' => Yii::$app->user->id,':is_train' => Group::MODE_GROUP,':status'=>Group::STATUS_GRADUATION] )->queryAll();       
        }else{
            if($model->group->status==Group::STATUS_GRADUATION) {
                $sql1 = "status=:status";
            }else{
                $sql1 = "status<>:status";
            }
            $group_datas = Yii::$app->db->createCommand('SELECT id,name FROM {{%group}}  WHERE id<>:gid AND created_by=:id AND is_train=:is_train AND status<>:status',
            [':gid' => $model->group->id,':id' => Yii::$app->user->id,':is_train' => Group::MODE_GROUP,':status'=>Group::STATUS_GRADUATION] )->queryAll();         
        }

        return $this->render('update', [
            'model' => $model,
            'group_datas' => $group_datas,
            'announcements' => $announcements,
            'newAnnouncement' => $newAnnouncement
        ]);
    }

    public function actionClone()
    {
        if (($post = Yii::$app->request->post())) {
            $contest_id = $post['contest_id'];
            $group_id = $post['group_id'];
            $model = $this->findModel($contest_id);

            $count = (new Query())->select('id')
            ->from('{{%contest}}')
            ->where(['title' => $model->title,'group_id' => $group_id])
            ->count();
            if($count>0) {
                return "目标小组中已经存在标题为 [<font color=red>$model->title</font>] 的比赛。";
            }
            
            $newContest = new Contest();
            $newContest->group_id = $group_id;
            $newContest->title = $model->title;
            $dateOld = \DateTime::createFromFormat('Y-m-d H:i:s',$model->start_time);
            $dateNew =  new \DateTime('today ' . $dateOld->format('H:i:s'));
            $newContest->start_time = $dateNew->format('Y-m-d H:i:s');
            $dateEnd = \DateTime::createFromFormat('Y-m-d H:i:s',$model->end_time);
            if($dateEnd->format('Y')!="9999"){
                $daysDiff = $dateNew->diff($dateOld)->days; // 获取绝对天数差
                $dateEnd->modify("+$daysDiff days");
            }
            $newContest->end_time = $dateEnd->format('Y-m-d H:i:s');
            $newContest->lock_board_time = $model->lock_board_time;
            $newContest->status = $model->status;
            $newContest->editorial = $model->editorial;
            $newContest->description = $model->description;
            $newContest->type = $model->type;
            $newContest->scenario = $model->scenario;
            $newContest->created_by = Yii::$app->user->id;
            $newContest->language = $model->language;
            $newContest->invite_code = $model->invite_code;
            $newContest->ext_link = $model->ext_link;
            $newContest->enable_print = $model->enable_print;
            $newContest->enable_clarify = $model->enable_clarify;
            $newContest->show_solution = $model->show_solution;
            $newContest->punish_time = $model->punish_time;
            $newContest->enable_board = $model->enable_board;
            $newContest->save();
            $problems = $model->problems;
            foreach ($problems as $key => $p) {
                Yii::$app->db->createCommand()->insert('{{%contest_problem}}', [
                    'problem_id' => $p['problem_id'],
                    'contest_id' => $newContest->id,
                    'num' => $p['num']
                ])->execute();
            }
            return "[<font color=red>$model->title</font>] 已经成功克隆到指定小组中。";
        }
        
    }

    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        ContestUser::deleteAll(['contest_id' => $model->id]);
        ContestProblem::deleteAll(['contest_id' => $model->id]);
        Solution::deleteAll(['contest_id' => $model->id]);
        $groupId = $model->group_id;
        $model->delete();
        Yii::$app->session->setFlash('success', Yii::t('app', '已删除'));
        return $this->redirect(['/group/view', 'id' => $groupId]);
    }

    /**
     * @param int $id
     * @return Homework|null
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    protected function findModel($id)
    {
        if (($model = Homework::findOne($id)) !== null) {
            if ($model->hasPermission()) {
                return $model;
            } else {
                throw new ForbiddenHttpException(Yii::t('app', 'You are not allowed to perform this action.'));
            }
        }
        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
}
